Iteration comes in different forms. When you want event based iteration, use while statements. Otherwise, for statements are a suitable option. You are probably familiar with while statements from other programming languages, so use cases should be clear. We will talk about syntax and some basic examples regardless, however.
The syntax of a while statement in Python is the following:
while event:
// code
It is not much different from the for loop, and often constructs can be made similar. Let's look at a few examples.
Example 1 Let's iterate over a list until all of the items are popped of.
In [8]:
lst = ["commie", 19.0, "The Dark Knight", 33]
while lst:
print(lst.pop())
How does this work? Well, the while loop will run as long as the lst does not evaluate to None (when it is theoretically empty). Because we print what we pop, we get to print out all of the items and then then when the lst is gone (there are no items).
Example 2 We print until we reach a number that is a multiple of 4 and 3.
In [22]:
# think: until number % 4 == 0 and number % 3 == 0
number = 1
while number % 4 != 0 or number % 3 != 0:
number += 1
print(number)